package com.yx.system.service.impl;

import com.yx.system.dao.demoMapper;
import com.yx.system.entity.demo;
import com.yx.system.service.demoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by wuye on 2017/12/1.
 */
@Service
@CacheConfig(cacheNames = "demo")
@Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
public class demoServiceImpl implements demoService {

    @Autowired
    private demoMapper demoMapper;

    ReentrantLock lock = new ReentrantLock();
    @Override
    @CachePut(key = "#p0.name")
    public demo save(demo d) {
        try {
            lock.lock();
            demoMapper.insert(d);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

        return demoMapper.selectByPrimaryKey(d.getId());
    }

    @Override
    @Cacheable(key = "#p0")
    public demo queryByName(String name) {
        return demoMapper.queryByName(name);
    }

    @Override
    @CachePut(key = "#p0.name")
    public demo update(demo d) {
        try{
            lock.lock();
            demoMapper.updateByPrimaryKey(d);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

        return demoMapper.selectByPrimaryKey(d.getId());
    }

    @Override
    @CacheEvict(key = "#p0")
    public void delee(int id) {
        try {
            lock.lock();
            demoMapper.deleteByPrimaryKey(id);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}
